<?php

namespace App\Http\Controllers\Manager;

use App\Helper;
use App\Http\Controllers\Controller;
use App\Models\ServerSpellMall;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MallSpellController extends Controller
{
    public $prefix='manager.server';

    public function index($id){
        $server=$this->CheckServer($id);

        if(!$server->spellMall){
            $ssm=new ServerSpellMall();
            $ssm->server_id=$id;
            $ssm->spellTree0='';
            $ssm->spellTree1='';
            $ssm->spellTree2='';
            $ssm->spellTree3='';
            $ssm->spellTree4='';
            $ssm->spellTree5='';
            $ssm->spellTree6='';
            $ssm->spellTree7='';
            $ssm->spellTree8='';
            $ssm->spellTree9='';
            $ssm->spellTree11='';
            $ssm->save();
        }
        // dd($server->spellMall);
        // Helper::setDataBaseConf('mysql_world',$server,'acore_world');
        return view($this->prefix.'.mallspell',['server'=>$server]);
    }

    public function info($id){
        $server=$this->CheckServer($id);
        return JsonResponse::create(['err'=>0,'data'=>$server->spellMall]);
    }

    public function saveConfig($id,Request $request){
        $server=$this->CheckServer($id);
        $spellPointRatio=$request->get('spellPointRatio');
        $status=$request->get('status');
        DB::table('server_spellmall')->where('server_id',$server->id)->update([
            'spellPointRatio'=>$spellPointRatio,
            'status'=>$status,
        ]);

        return JsonResponse::create(['err'=>0]);
    }


    public function getSpellInfo(Request $request){
        $id=$request->get('id');
        $str=file_get_contents('http://db.wowmanage.cn/?spell='.$id.'&domain=cn&power');
        $str=$this->cut('{','}',$str);
        $arr=json_decode('{'.$str.'}');
        return JsonResponse::create(['err'=>0,'data'=>$arr]);
    }

    function cut($begin,$end,$str){
        $b = mb_strpos($str,$begin) + mb_strlen($begin);
        $e = mb_strpos($str,$end) - $b;
        return mb_substr($str,$b,$e);
    }
    public function save(Request $request,$id){
        $server=$this->CheckServer($id);
        $data=$request->get('data');
        $type=$request->get('type');

        DB::table('server_spellmall')->where('server_id',$server->id)->update([
            'spellTree'.$type=>$data
        ]);
        return JsonResponse::create(['err'=>0]);
    }

}
